<template>
  <section class="space-y-4 pb-16">
    <!-- 搜索和筛选卡片 -->
    <div class="bg-white/80 backdrop-blur-lg rounded-2xl p-6 shadow-xl border border-white/50 mb-6 relative z-[1000]">
      <!-- 文字搜索 -->
      <div class="mb-5">
        <div class="relative">
          <svg class="absolute left-3 top-1/2 transform -translate-y-1/2 w-4 h-4 text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="m21 21-6-6m2-5a7 7 0 1 1-14 0 7 7 0 0 1 14 0Z"/>
          </svg>
          <input 
            type="text" 
            v-model="searchText" 
            placeholder="搜索站点名称、地址等"
            class="w-full pl-10 pr-4 py-3 bg-white/50 border border-gray-200/50 rounded-xl text-sm focus:outline-none focus:ring-2 focus:ring-blue-500/50 focus:border-transparent transition-all duration-300"
          />
        </div>
      </div>

      <!-- 筛选条件 -->
      <div class="grid grid-cols-3 gap-4">
        <!-- 站点类型筛选 -->
        <div>
          <label class="block text-sm font-medium text-gray-700 mb-2">站点类型</label>
          <div class="relative z-[2000]">
            <button 
              @click="toggleTypeDropdown" 
              class="w-full px-3 py-2.5 bg-white/50 border border-gray-200/50 rounded-xl text-sm text-left focus:outline-none focus:ring-2 focus:ring-blue-500/50 focus:border-transparent transition-all duration-300"
            >
              <span class="truncate">{{ getTypeLabel(selectedType) }}</span>
              <svg class="absolute right-3 top-1/2 transform -translate-y-1/2 w-4 h-4 text-gray-400 pointer-events-none" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="m19 9-7 7-7-7"/>
              </svg>
            </button>
            
            <!-- 站点类型下拉菜单 -->
            <div v-if="showTypeDropdown" class="absolute top-full left-0 mt-1 w-full bg-white rounded-xl shadow-2xl border border-gray-200 overflow-hidden animate-slide-up z-[100]" @click.stop>
              <button 
                v-for="option in typeOptions" 
                :key="option.value"
                @click="selectType(option.value)"
                class="w-full px-4 py-3 text-left hover:bg-gray-50 transition-colors text-sm"
                :class="{'bg-blue-50 text-blue-600': selectedType === option.value}"
              >
                {{ option.label }}
              </button>
            </div>
          </div>
        </div>

        <!-- 接入方式筛选 -->
        <div>
          <label class="block text-sm font-medium text-gray-700 mb-2">接入方式</label>
          <div class="relative z-[2000]">
            <button 
              @click="toggleAccessDropdown" 
              class="w-full px-3 py-2.5 bg-white/50 border border-gray-200/50 rounded-xl text-sm text-left focus:outline-none focus:ring-2 focus:ring-blue-500/50 focus:border-transparent transition-all duration-300"
            >
              <span class="truncate">{{ getAccessLabel(selectedAccess) }}</span>
              <svg class="absolute right-3 top-1/2 transform -translate-y-1/2 w-4 h-4 text-gray-400 pointer-events-none" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="m19 9-7 7-7-7"/>
              </svg>
            </button>
            
            <!-- 接入方式下拉菜单 -->
            <div v-if="showAccessDropdown" class="absolute top-full left-0 mt-1 w-full bg-white rounded-xl shadow-2xl border border-gray-200 overflow-hidden animate-slide-up z-[100]" @click.stop>
              <button 
                v-for="option in accessOptions" 
                :key="option.value"
                @click="selectAccess(option.value)"
                class="w-full px-4 py-3 text-left hover:bg-gray-50 transition-colors text-sm"
                :class="{'bg-blue-50 text-blue-600': selectedAccess === option.value}"
              >
                {{ option.label }}
              </button>
            </div>
          </div>
        </div>

        <!-- 站点状态筛选 -->
        <div>
          <label class="block text-sm font-medium text-gray-700 mb-2">站点状态</label>
          <div class="relative z-[2000]">
            <button 
              @click="toggleStatusDropdown" 
              class="w-full px-3 py-2.5 bg-white/50 border border-gray-200/50 rounded-xl text-sm text-left focus:outline-none focus:ring-2 focus:ring-blue-500/50 focus:border-transparent transition-all duration-300"
            >
              <span class="truncate">{{ getStatusLabel(selectedStatus) }}</span>
              <svg class="absolute right-3 top-1/2 transform -translate-y-1/2 w-4 h-4 text-gray-400 pointer-events-none" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="m19 9-7 7-7-7"/>
              </svg>
            </button>
            
            <!-- 站点状态下拉菜单 -->
            <div v-if="showStatusDropdown" class="absolute top-full left-0 mt-1 w-full bg-white rounded-xl shadow-2xl border border-gray-200 overflow-hidden animate-slide-up z-[100]" @click.stop>
              <button 
                v-for="option in statusFilterOptions" 
                :key="option.value"
                @click="selectStatus(option.value)"
                class="w-full px-4 py-3 text-left hover:bg-gray-50 transition-colors text-sm"
                :class="{'bg-blue-50 text-blue-600': selectedStatus === option.value}"
              >
                {{ option.label }}
              </button>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 筛选结果统计 -->
    <div v-if="!loading && !loadError" class="flex justify-between items-center mb-4 px-4">
      <div class="text-sm text-gray-600">筛选结果:</div>
      <div class="text-sm text-gray-900 font-medium">共计{{ filteredStations.length }}个</div>
    </div>

    <!-- 加载状态 -->
    <div v-if="loading" class="flex justify-center items-center py-8">
      <div class="animate-spin rounded-full h-8 w-8 border-b-2 border-blue-500"></div>
      <span class="ml-2 text-gray-600">加载中...</span>
    </div>

    <!-- 错误状态 -->
    <div v-else-if="loadError" class="bg-red-50 border border-red-200 rounded-lg p-6 text-center">
      <div class="flex flex-col items-center justify-center space-y-3">
        <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" class="w-12 h-12 text-red-400">
          <path stroke-linecap="round" stroke-linejoin="round" stroke-width="1.5" d="M12 9v3.75m9-.75a9 9 0 11-18 0 9 9 0 0118 0zm-9 3.75h.008v.008H12v-.008z"/>
        </svg>
        <div class="text-red-700 font-medium">加载失败</div>
        <div class="text-red-600 text-sm">{{ loadError }}</div>
        <button @click="fetchStations" class="mt-2 px-4 py-2 bg-red-600 text-white rounded-md text-sm hover:bg-red-700 transition">
          重新加载
        </button>
      </div>
    </div>

    <div v-else class="space-y-3">
      <div v-if="filteredStations.length === 0" class="bg-white rounded-lg p-8 shadow-sm border border-gray-100 text-center">
        <div class="flex flex-col items-center justify-center space-y-3">
          <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" class="w-12 h-12 text-gray-300">
            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="1.5" d="M12 2C13.1 2 14 2.9 14 4C14 5.1 13.1 6 12 6C10.9 6 10 5.1 10 4C10 2.9 10.9 2 12 2ZM21 9V7C21 5.9 20.1 5 19 5H5C3.9 5 3 5.9 3 7V9C3 10.1 3.9 11 5 11H19C20.1 11 21 10.1 21 9ZM5 13H7V21H5V13ZM9 13H11V21H9V13ZM13 13H15V21H13V13ZM17 13H19V21H17V13Z"/>
          </svg>
          <div class="text-gray-500 text-sm">暂无符合条件的站点</div>
          <div class="text-gray-400 text-xs">请尝试调整筛选条件</div>
        </div>
      </div>
      
      <div v-else v-for="station in filteredStations" :key="station.id" class="relative rounded-2xl bg-white border-2 border-gray-200 shadow-sm overflow-hidden hover:shadow-md transition">
        <div class="p-4">
          
          <!-- 第一行：站名和运营状态 -->
          <div class="flex items-center justify-between gap-3">
            <div class="text-xl font-semibold text-gray-900 tracking-tight">{{ station.name }}</div>
            <div 
              @click="openStatusModal(station)" 
              :class="['inline-flex items-center justify-center px-3 py-1.5 rounded-md border text-sm font-medium select-none leading-tight w-fit cursor-pointer hover:opacity-80 transition-opacity', statusConf(station).badge]"
            >
              <span>{{ statusConf(station).top }}{{ statusConf(station).bottom }}</span>
            </div>
          </div>

          <!-- 分割线 -->
          <div class="w-full h-px bg-gray-200 mt-2 mb-2"></div>

          <!-- 第二行：运营商和数量等信息，右侧放置按钮 -->
          <div class="flex items-center justify-between">
            <div class="space-y-2 text-sm text-gray-600">
              <div>地址：FeeYee智能系统</div>
              <div>充电桩数量：{{ station.pileCount }}</div>
            </div>
            
            <!-- 站点详情和设备管理按钮 -->
            <div class="flex gap-2">
              <div @click="goToStationDetail(station)" class="inline-flex flex-col items-center justify-center px-3 py-2 rounded-md border text-sm font-medium select-none leading-tight bg-purple-100 text-purple-800 border-purple-200 shadow-xs cursor-pointer hover:opacity-80 transition-opacity">
                <span>站点</span>
                <span>详情</span>
              </div>
              <div @click="goToDeviceManagement" class="inline-flex flex-col items-center justify-center px-3 py-2 rounded-md border text-sm font-medium select-none leading-tight bg-blue-100 text-blue-800 border-blue-200 shadow-xs cursor-pointer hover:opacity-80 transition-opacity">
                <span>设备</span>
                <span>管理</span>
              </div>
            </div>
          </div>

          <!-- 枪位监控 -->
          <div class="mt-3 bg-white rounded-xl p-4 shadow-sm border border-gray-100 relative">
            <!-- 左上角枪位实时监控标签 -->
            <div class="absolute -top-2 -left-2 inline-flex items-center justify-center px-2 py-1 bg-indigo-500 text-white text-xs font-medium rounded-md shadow-sm select-none">
              枪位实时监控
            </div>
            <div class="grid grid-cols-5 gap-2 text-center">
              <div class="rounded-xl bg-emerald-50 p-2 text-center">
                <div class="w-full inline-flex items-center justify-center gap-0.5 text-[12px] sm:text-[13px] text-gray-700 whitespace-nowrap leading-none -ml-0.5">
                  <span>充电中</span>
                </div>
                <div class="mt-0.5 text-sm font-normal text-gray-900 whitespace-nowrap tracking-tight leading-tight">{{ station.gunStatus.charging }}</div>
              </div>
              <div class="rounded-xl bg-sky-50 p-2 text-center">
                <div class="w-full inline-flex items-center justify-center gap-0.5 text-[12px] sm:text-[13px] text-gray-700 whitespace-nowrap leading-none -ml-0.5">
                  <span>空闲</span>
                </div>
                <div class="mt-0.5 text-sm font-normal text-gray-900 whitespace-nowrap tracking-tight leading-tight">{{ station.gunStatus.idle }}</div>
              </div>
              <div class="rounded-xl bg-yellow-50 p-2 text-center">
                <div class="w-full inline-flex items-center justify-center gap-0.5 text-[12px] sm:text-[13px] text-gray-700 whitespace-nowrap leading-none -ml-0.5">
                  <span>占用</span>
                </div>
                <div class="mt-0.5 text-sm font-normal text-gray-900 whitespace-nowrap tracking-tight leading-tight">{{ station.gunStatus.occupied }}</div>
              </div>
              <div class="rounded-xl bg-red-50 p-2 text-center">
                <div class="w-full inline-flex items-center justify-center gap-0.5 text-[12px] sm:text-[13px] text-gray-700 whitespace-nowrap leading-none -ml-0.5">
                  <span>故障</span>
                </div>
                <div class="mt-0.5 text-sm font-normal text-gray-900 whitespace-nowrap tracking-tight leading-tight">{{ station.gunStatus.fault }}</div>
              </div>
              <div class="rounded-xl bg-gray-50 p-2 text-center">
                <div class="w-full inline-flex items-center justify-center gap-0.5 text-[12px] sm:text-[13px] text-gray-700 whitespace-nowrap leading-none -ml-0.5">
                  <span>离线</span>
                </div>
                <div class="mt-0.5 text-sm font-normal text-gray-900 whitespace-nowrap tracking-tight leading-tight">{{ station.gunStatus.offline }}</div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </section>

  <!-- 状态修改弹窗 -->
  <div v-if="showStatusModal" class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-[1500]">
    <div class="bg-white rounded-2xl p-6 w-full max-w-md mx-4 shadow-2xl">
      <!-- 弹窗标题 -->
      <div class="text-lg font-semibold text-gray-900 mb-4">修改站点状态</div>
      
      <!-- 当前站点信息 -->
      <div class="mb-4 p-3 bg-gray-50 rounded-lg">
        <div class="text-sm text-gray-600">站点名称</div>
        <div class="font-medium text-gray-900">{{ currentStation?.name }}</div>
      </div>
      
      <!-- 当前状态显示 -->
      <div class="mb-4">
        <div class="text-sm text-gray-600 mb-2">当前状态</div>
        <div class="inline-flex items-center px-3 py-1.5 rounded-md border text-sm font-medium" :class="statusConf(currentStation).badge">
          <span>{{ statusConf(currentStation).top }}{{ statusConf(currentStation).bottom }}</span>
        </div>
      </div>
      
      <!-- 状态选择 -->
      <div class="mb-6">
        <div class="text-sm text-gray-600 mb-2">选择新状态</div>
        <div class="space-y-2">
          <div 
            v-for="option in statusOptions" 
            :key="option.value"
            @click="selectedNewStatus = option.value"
            :class="['flex items-center p-3 rounded-lg border cursor-pointer transition-colors', selectedNewStatus === option.value ? 'border-blue-500 bg-blue-50' : 'border-gray-200 hover:border-gray-300']"
          >
            <input 
              type="radio" 
              :value="option.value" 
              v-model="selectedNewStatus"
              class="mr-3 text-blue-600 focus:ring-blue-500"
            >
            <div class="flex items-center justify-between flex-1">
              <span class="font-medium text-gray-900">{{ option.label }}</span>
              <div class="inline-flex items-center px-2 py-1 rounded-md border text-xs font-medium" :class="option.color">
                预览
              </div>
            </div>
          </div>
        </div>
      </div>
      
      <!-- 操作按钮 -->
      <div class="flex gap-3">
        <button 
          @click="closeStatusModal"
          class="flex-1 px-4 py-2 bg-gray-100 text-gray-700 rounded-lg font-medium hover:bg-gray-200 transition-colors"
        >
          取消
        </button>
        <button 
          @click="saveStationStatus"
          :disabled="!selectedNewStatus || selectedNewStatus === currentStation?.status"
          class="flex-1 px-4 py-2 bg-blue-600 text-white rounded-lg font-medium hover:bg-blue-700 transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
        >
          保存
        </button>
      </div>
    </div>
  </div>

  <!-- 自定义确认弹窗 -->
  <div v-if="showConfirmModal" class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-[1500]">
    <div class="bg-white rounded-2xl p-6 w-full max-w-sm mx-4 shadow-2xl">
      <!-- 警告图标 -->
      <div class="flex justify-center mb-4">
        <div class="w-12 h-12 bg-amber-100 rounded-full flex items-center justify-center">
          <svg class="w-6 h-6 text-amber-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z"/>
          </svg>
        </div>
      </div>
      
      <!-- 确认信息 -->
      <div class="text-center mb-6">
        <div class="text-lg font-semibold text-gray-900 mb-2">确认操作</div>
        <div class="text-sm text-gray-600 leading-relaxed">{{ confirmMessage }}</div>
      </div>
      
      <!-- 操作按钮 -->
      <div class="flex gap-3">
        <button 
          @click="cancelConfirm"
          class="flex-1 px-4 py-2 bg-gray-100 text-gray-700 rounded-lg font-medium hover:bg-gray-200 transition-colors"
        >
          取消
        </button>
        <button 
          @click="executeConfirm"
          class="flex-1 px-4 py-2 bg-blue-600 text-white rounded-lg font-medium hover:bg-blue-700 transition-colors"
        >
          确认
        </button>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, onUnmounted } from 'vue'
import { useRouter } from 'vue-router'

const router = useRouter()

// 搜索条件
const searchText = ref('')
const selectedStatus = ref('')
const selectedType = ref('')
const selectedAccess = ref('')

// 下拉菜单显示状态
const showTypeDropdown = ref(false)
const showAccessDropdown = ref(false)
const showStatusDropdown = ref(false)

// 筛选选项数据
const typeOptions = [
  { value: '', label: '全部' },
  { value: 'personal', label: '个人' },
  { value: 'public', label: '公共' }
]

const accessOptions = [
  { value: '', label: '全部' },
  { value: 'direct', label: '直连' },
  { value: 'api', label: 'API接入' },
  { value: 'cloud', label: '云平台' }
]

const statusFilterOptions = [
  { value: '', label: '全部' },
  { value: 'normal', label: '正常运营' },
  { value: 'stopped', label: '停止运营' },
  { value: 'maintenance', label: '维护中' },
  { value: 'offline', label: '离线' }
]

// 数据
const loading = ref(false)
const loadError = ref('')
const stations = ref([])

// 状态弹窗相关
const showStatusModal = ref(false)
const currentStation = ref(null)
const selectedNewStatus = ref('')

// 确认弹窗相关
const showConfirmModal = ref(false)
const confirmMessage = ref('')
const confirmAction = ref(null)

// 所有可用状态
const statusOptions = [
  { value: 'normal', label: '正常运营', color: 'bg-emerald-100 text-emerald-800 border-emerald-200' },
  { value: 'stopped', label: '停止运营', color: 'bg-gray-100 text-gray-700 border-gray-200' },
  { value: 'maintenance', label: '维护中', color: 'bg-yellow-100 text-yellow-800 border-yellow-200' },
  { value: 'offline', label: '离线状态', color: 'bg-red-100 text-red-800 border-red-200' }
]

// 模拟数据
const mockStations = [
  {
    id: 1,
    name: '上海浦东充电站',
    status: 'normal',
    operator: '国家电网',
    manager: '李经理',
    pileCount: 15,
    gunStatus: {
      charging: 3,
      idle: 8,
      occupied: 2,
      fault: 1,
      offline: 1
    }
  },
  {
    id: 2,
    name: '北京朝阳充电站',
    status: 'normal',
    operator: '特来电',
    manager: '王经理',
    pileCount: 12,
    gunStatus: {
      charging: 2,
      idle: 7,
      occupied: 1,
      fault: 0,
      offline: 2
    }
  },
  {
    id: 3,
    name: '广州天河充电站',
    status: 'stopped',
    operator: '星星充电',
    manager: '张经理',
    pileCount: 8,
    gunStatus: {
      charging: 0,
      idle: 0,
      occupied: 0,
      fault: 3,
      offline: 5
    }
  },
  {
    id: 4,
    name: '深圳南山充电站',
    status: 'normal',
    operator: '云快充',
    manager: '陈经理',
    pileCount: 20,
    gunStatus: {
      charging: 5,
      idle: 10,
      occupied: 3,
      fault: 1,
      offline: 1
    }
  }
]

// 过滤后的站点列表
const filteredStations = computed(() => {
  return stations.value.filter(station => {
    // 文字搜索过滤
    const textMatch = !searchText.value || 
      station.name.toLowerCase().includes(searchText.value.toLowerCase())
    
    // 站点状态过滤
    const statusMatch = !selectedStatus.value || station.status === selectedStatus.value
    
    // 站点类型过滤（这里暂时用固定值，后续可以根据字典匹配）
    const typeMatch = !selectedType.value
    
    // 接入方式过滤（这里暂时用固定值，后续可以根据字典匹配）
    const accessMatch = !selectedAccess.value
    
    return textMatch && statusMatch && typeMatch && accessMatch
  })
})

// 站点状态配置函数
const statusConf = (station) => {
  const status = station.status
  
  if (status === 'normal') {
    return {
      top: '正常', 
      bottom: '运营',
      badge: 'bg-emerald-100 text-emerald-800 border-emerald-200 shadow-xs'
    }
  } else if (status === 'stopped') {
    return {
      top: '停止', 
      bottom: '运营',
      badge: 'bg-gray-100 text-gray-700 border-gray-200 shadow-xs'
    }
  } else if (status === 'maintenance') {
    return {
      top: '维护', 
      bottom: '中',
      badge: 'bg-yellow-100 text-yellow-800 border-yellow-200 shadow-xs'
    }
  } else if (status === 'offline') {
    return {
      top: '离线', 
      bottom: '状态',
      badge: 'bg-red-100 text-red-800 border-red-200 shadow-xs'
    }
  }
  
  // 默认状态
  return {
    top: '未知', 
    bottom: '状态',
    badge: 'bg-gray-100 text-gray-700 border-gray-200 shadow-xs'
  }
}

// 打开状态弹窗
const openStatusModal = (station) => {
  currentStation.value = station
  selectedNewStatus.value = station.status
  showStatusModal.value = true
}

// 关闭状态弹窗
const closeStatusModal = () => {
  showStatusModal.value = false
  currentStation.value = null
  selectedNewStatus.value = ''
}

// 显示确认弹窗
const showConfirm = (message, action) => {
  confirmMessage.value = message
  confirmAction.value = action
  showConfirmModal.value = true
}

// 执行确认操作
const executeConfirm = async () => {
  if (confirmAction.value) {
    await confirmAction.value()
  }
  showConfirmModal.value = false
  confirmMessage.value = ''
  confirmAction.value = null
}

// 取消确认
const cancelConfirm = () => {
  showConfirmModal.value = false
  confirmMessage.value = ''
  confirmAction.value = null
}

// 显示成功提示
const showSuccess = (message) => {
  // 创建临时成功提示
  const successToast = document.createElement('div')
  successToast.className = 'fixed top-4 right-4 bg-green-500 text-white px-6 py-3 rounded-lg shadow-lg z-[2000] flex items-center space-x-2 transform transition-all duration-300 translate-x-full'
  successToast.innerHTML = `
    <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
      <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5 13l4 4L19 7"></path>
    </svg>
    <span>${message}</span>
  `
  document.body.appendChild(successToast)
  
  // 触发动画
  setTimeout(() => {
    successToast.classList.remove('translate-x-full')
    successToast.classList.add('translate-x-0')
  }, 100)
  
  // 3秒后自动移除
  setTimeout(() => {
    successToast.classList.remove('translate-x-0')
    successToast.classList.add('translate-x-full')
    setTimeout(() => {
      document.body.removeChild(successToast)
    }, 300)
  }, 3000)
}

// 跳转到站点详情页
const goToStationDetail = (station) => {
  // 直接使用路由跳转
  router.push('/station-detail')
}

// 跳转到设备管理页
const goToDeviceManagement = () => {
  // 直接使用路由跳转
  router.push('/device-management')
}

// 下拉菜单交互函数
const toggleTypeDropdown = () => {
  showTypeDropdown.value = !showTypeDropdown.value
  // 关闭其他下拉菜单
  showAccessDropdown.value = false
  showStatusDropdown.value = false
}

const toggleAccessDropdown = () => {
  showAccessDropdown.value = !showAccessDropdown.value
  // 关闭其他下拉菜单
  showTypeDropdown.value = false
  showStatusDropdown.value = false
}

const toggleStatusDropdown = () => {
  showStatusDropdown.value = !showStatusDropdown.value
  // 关闭其他下拉菜单
  showTypeDropdown.value = false
  showAccessDropdown.value = false
}

const selectType = (value) => {
  selectedType.value = value
  showTypeDropdown.value = false
}

const selectAccess = (value) => {
  selectedAccess.value = value
  showAccessDropdown.value = false
}

const selectStatus = (value) => {
  selectedStatus.value = value
  showStatusDropdown.value = false
}

// 获取标签文本
const getTypeLabel = (value) => {
  const option = typeOptions.find(opt => opt.value === value)
  return option ? option.label : '全部'
}

const getAccessLabel = (value) => {
  const option = accessOptions.find(opt => opt.value === value)
  return option ? option.label : '全部'
}

const getStatusLabel = (value) => {
  const option = statusFilterOptions.find(opt => opt.value === value)
  return option ? option.label : '全部'
}

// 简化的详情页面显示（备用方案）
const showStationDetailSimple = (station) => {
  // 使用路由跳转到站点详情页面
  router.push('/station-detail')
  return
  const detailOverlay = document.getElementById('station-detail-overlay')
  if (detailOverlay) {
    detailOverlay.innerHTML = `
      <div class="min-h-screen bg-gray-50">
        <!-- 顶部导航栏 -->
        <div class="bg-white shadow-sm sticky top-0 z-40">
          <div class="flex items-center justify-between px-4 py-3">
            <div class="flex items-center gap-3">
              <button onclick="closeStationDetail()" class="p-2 hover:bg-gray-100 rounded-lg transition-colors">
                <svg class="w-5 h-5 text-gray-700" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 19l-7-7 7-7"/>
                </svg>
              </button>
              <div class="text-lg font-semibold text-gray-900">站点详情</div>
            </div>
          </div>
        </div>

        <!-- 主要内容 -->
        <div class="pb-20">
          <!-- 图片轮播占位 -->
          <div class="relative h-64 bg-gray-200 overflow-hidden">
            <div class="w-full h-full flex items-center justify-center text-gray-500">
              <div class="text-center">
                <div class="text-sm">站点图片轮播区域</div>
              </div>
            </div>
          </div>

          <!-- 站点名称 -->
          <div class="px-4 py-3 bg-white">
            <div class="flex items-center gap-2">
              <div class="w-8 h-8 bg-green-100 rounded-lg flex items-center justify-center flex-shrink-0">
                <svg class="w-4 h-4 text-green-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 21V5a2 2 0 00-2-2H7a2 2 0 00-2 2v16m14 0h2m-2 0h-5m-9 0H3m2 0h5M17 8l2 2m0 0l2 2m-2-2v4m-4 2H7m4-6l2-2m0 0l2 2m-2-2v4"/>
                </svg>
              </div>
              <h1 class="text-xl font-bold text-gray-900">${station.name}</h1>
            </div>
          </div>

          <!-- 基本信息卡片 -->
          <div class="relative rounded-2xl bg-white border-2 border-gray-200 shadow-sm overflow-hidden mx-4 mt-4">
            <div class="p-4">
              <div class="flex items-center justify-between mb-4">
                <div class="flex items-center gap-2">
                  <div class="w-2 h-2 bg-green-500 rounded-full"></div>
                  <span class="font-medium text-gray-900">基本信息</span>
                </div>
              </div>

              <div class="space-y-4">
                <!-- 运营时间 -->
                <div class="flex gap-3">
                  <div class="w-8 h-8 bg-blue-100 rounded-lg flex items-center justify-center flex-shrink-0 self-center">
                    <svg class="w-4 h-4 text-blue-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                      <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 8v4l3 3m6-3a9 9 0 11-18 0 9 9 0 0118 0z"/>
                    </svg>
                  </div>
                  <div class="flex-1">
                    <div class="text-sm font-medium text-gray-900">运营时间</div>
                    <div class="text-sm text-gray-600">周一至周日 00:00~24:00</div>
                  </div>
                </div>

                <!-- 详细地址 -->
                <div class="flex gap-3">
                  <div class="w-8 h-8 bg-red-100 rounded-lg flex items-center justify-center flex-shrink-0 self-center">
                    <svg class="w-4 h-4 text-red-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                      <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M17.657 16.657L13.414 20.9a1.998 1.998 0 01-2.827 0l-4.244-4.243a8 8 0 1111.314 0z"/>
                      <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 11a3 3 0 11-6 0 3 3 0 016 0z"/>
                    </svg>
                  </div>
                  <div class="flex-1">
                    <div class="text-sm font-medium text-gray-900">详细地址</div>
                    <div class="text-sm text-gray-600">FeeYee智能系统</div>
                    <div class="text-xs text-gray-500 mt-1">坐标: 31.2304°N, 121.4737°E</div>
                  </div>
                </div>

                <!-- 运营商信息 -->
                <div class="flex gap-3">
                  <div class="w-8 h-8 bg-purple-100 rounded-lg flex items-center justify-center flex-shrink-0 self-center">
                    <svg class="w-4 h-4 text-purple-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                      <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 21V5a2 2 0 00-2-2H7a2 2 0 00-2 2v16m14 0h2m-2 0h-5m-9 0H3m2 0h5M9 7h1m-1 4h1m4-4h1m-1 4h1m-5 10v-5a1 1 0 011-1h2a1 1 0 011 1v5m-4 0h4"/>
                    </svg>
                  </div>
                  <div class="flex-1">
                    <div class="text-sm font-medium text-gray-900">运营商</div>
                    <div class="text-sm text-gray-600">FeeYee智能系统</div>
                    <div class="text-xs text-gray-500 mt-1">400-888-9999</div>
                  </div>
                </div>
              </div>
            </div>
          </div>

          <!-- 技术信息卡片 -->
          <div class="relative rounded-2xl bg-white border-2 border-gray-200 shadow-sm overflow-hidden mx-4 mt-4">
            <div class="p-4">
              <div class="flex items-center gap-2 mb-4">
                <div class="w-2 h-2 bg-blue-500 rounded-full"></div>
                <span class="font-medium text-gray-900">技术信息</span>
              </div>

              <div class="grid grid-cols-2 gap-4">
                <div class="bg-gray-50 rounded-lg p-3">
                  <div class="text-xs text-gray-600 mb-1">运营类型</div>
                  <div class="text-sm font-medium text-gray-900">自营</div>
                </div>
                <div class="bg-gray-50 rounded-lg p-3">
                  <div class="text-xs text-gray-600 mb-1">接入方式</div>
                  <div class="text-sm font-medium text-gray-900">直连</div>
                </div>
                <div class="bg-gray-50 rounded-lg p-3">
                  <div class="text-xs text-gray-600 mb-1">站点类型</div>
                  <div class="text-sm font-medium text-gray-900">公用</div>
                </div>
                <div class="bg-gray-50 rounded-lg p-3">
                  <div class="text-xs text-gray-600 mb-1">建设场所</div>
                  <div class="text-sm font-medium text-gray-900">工业园区</div>
                </div>
                <div class="bg-gray-50 rounded-lg p-3 col-span-2">
                  <div class="text-xs text-gray-600 mb-1">站点位置</div>
                  <div class="text-sm font-medium text-gray-900">地面</div>
                </div>
              </div>
            </div>
          </div>

          <!-- 计费规则卡片 -->
          <div class="relative rounded-2xl bg-white border-2 border-gray-200 shadow-sm overflow-hidden mx-4 mt-4">
            <div class="p-4">
              <div class="flex items-center gap-2 mb-4">
                <div class="w-2 h-2 bg-orange-500 rounded-full"></div>
                <span class="font-medium text-gray-900">计费规则</span>
              </div>

              <!-- 时段定义 -->
              <div class="mb-4">
                <div class="text-sm text-gray-600 mb-3">时段划分</div>
                <div class="space-y-2">
                  <div class="flex items-center justify-between p-3 bg-gradient-to-r from-red-50 to-orange-50 rounded-lg">
                    <div class="flex items-center gap-2">
                      <div class="w-2 h-2 bg-red-500 rounded-full"></div>
                      <span class="text-sm font-medium text-gray-900">尖</span>
                    </div>
                    <span class="text-sm text-gray-700">12:00 - 18:00</span>
                  </div>
                  <div class="flex items-center justify-between p-3 bg-gradient-to-r from-orange-50 to-yellow-50 rounded-lg">
                    <div class="flex items-center gap-2">
                      <div class="w-2 h-2 bg-orange-500 rounded-full"></div>
                      <span class="text-sm font-medium text-gray-900">峰</span>
                    </div>
                    <span class="text-sm text-gray-700">00:00 - 06:00</span>
                  </div>
                  <div class="flex items-center justify-between p-3 bg-gradient-to-r from-blue-50 to-cyan-50 rounded-lg">
                    <div class="flex items-center gap-2">
                      <div class="w-2 h-2 bg-blue-500 rounded-full"></div>
                      <span class="text-sm font-medium text-gray-900">平</span>
                    </div>
                    <span class="text-sm text-gray-700">18:00 - 24:00</span>
                  </div>
                  <div class="flex items-center justify-between p-3 bg-gradient-to-r from-green-50 to-emerald-50 rounded-lg">
                    <div class="flex items-center gap-2">
                      <div class="w-2 h-2 bg-green-500 rounded-full"></div>
                      <span class="text-sm font-medium text-gray-900">谷</span>
                    </div>
                    <span class="text-sm text-gray-700">06:00 - 12:00</span>
                  </div>
                </div>
              </div>

              <!-- 价格表 -->
              <div>
                <div class="text-sm text-gray-600 mb-3">价格标准</div>
                <div class="grid grid-cols-2 gap-3">
                  <div class="bg-gray-50 rounded-lg p-3">
                    <div class="text-xs text-gray-600 mb-2">电费单价 (元/度)</div>
                    <div class="space-y-1">
                      <div class="flex justify-between items-center">
                        <span class="text-xs text-gray-500">尖</span>
                        <span class="text-sm font-medium text-gray-900">¥0.9</span>
                      </div>
                      <div class="flex justify-between items-center">
                        <span class="text-xs text-gray-500">峰</span>
                        <span class="text-sm font-medium text-gray-900">¥0.9</span>
                      </div>
                      <div class="flex justify-between items-center">
                        <span class="text-xs text-gray-500">平</span>
                        <span class="text-sm font-medium text-gray-900">¥0.9</span>
                      </div>
                      <div class="flex justify-between items-center">
                        <span class="text-xs text-gray-500">谷</span>
                        <span class="text-sm font-medium text-gray-900">¥0.9</span>
                      </div>
                    </div>
                  </div>
                  <div class="bg-gray-50 rounded-lg p-3">
                    <div class="text-xs text-gray-600 mb-2">服务费单价 (元/度)</div>
                    <div class="space-y-1">
                      <div class="flex justify-between items-center">
                        <span class="text-xs text-gray-500">尖</span>
                        <span class="text-sm font-medium text-gray-900">¥0.4</span>
                      </div>
                      <div class="flex justify-between items-center">
                        <span class="text-xs text-gray-500">峰</span>
                        <span class="text-sm font-medium text-gray-900">¥0.4</span>
                      </div>
                      <div class="flex justify-between items-center">
                        <span class="text-xs text-gray-500">平</span>
                        <span class="text-sm font-medium text-gray-900">¥0.4</span>
                      </div>
                      <div class="flex justify-between items-center">
                        <span class="text-xs text-gray-500">谷</span>
                        <span class="text-sm font-medium text-gray-900">¥0.4</span>
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>

        </div>
      </div>
    `
  }
}

// 关闭详情页面
window.closeStationDetail = function() {
  const detailOverlay = document.getElementById('station-detail-overlay')
  if (detailOverlay) {
    document.body.removeChild(detailOverlay)
  }
}

// 显示错误提示
const showError = (message) => {
  // 创建临时错误提示
  const errorToast = document.createElement('div')
  errorToast.className = 'fixed top-4 right-4 bg-red-500 text-white px-6 py-3 rounded-lg shadow-lg z-[2000] flex items-center space-x-2 transform transition-all duration-300 translate-x-full'
  errorToast.innerHTML = `
    <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
      <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12"></path>
    </svg>
    <span>${message}</span>
  `
  document.body.appendChild(errorToast)
  
  // 触发动画
  setTimeout(() => {
    errorToast.classList.remove('translate-x-full')
    errorToast.classList.add('translate-x-0')
  }, 100)
  
  // 3秒后自动移除
  setTimeout(() => {
    errorToast.classList.remove('translate-x-0')
    errorToast.classList.add('translate-x-full')
    setTimeout(() => {
      document.body.removeChild(errorToast)
    }, 300)
  }, 3000)
}

// 保存状态
const saveStationStatus = async () => {
  if (!currentStation.value || !selectedNewStatus.value) return
  
  const statusOption = statusOptions.find(option => option.value === selectedNewStatus.value)
  const message = `确认要将 "${currentStation.value.name}" 的状态修改为 "${statusOption.label}" 吗？`
  
  showConfirm(message, async () => {
    try {
      // 这里暂时模拟API调用
      await new Promise(resolve => setTimeout(resolve, 500))
      
      // 更新本地数据
      const stationIndex = stations.value.findIndex(s => s.id === currentStation.value.id)
      if (stationIndex !== -1) {
        stations.value[stationIndex].status = selectedNewStatus.value
      }
      
      // 关闭状态弹窗
      closeStatusModal()
      
      // 显示成功提示
      showSuccess('状态修改成功！')
      
    } catch (error) {
      console.error('修改状态失败:', error)
      showError('修改状态失败，请重试')
    }
  })
}

// 获取站点数据
const fetchStations = async () => {
  loading.value = true
  loadError.value = ''
  try {
    // 模拟API请求延迟
    await new Promise(resolve => setTimeout(resolve, 800))
    
    // 使用模拟数据
    stations.value = mockStations
    
  } catch (error) {
    const errorMsg = error.message || '网络错误，请检查连接'
    loadError.value = errorMsg
    console.error('获取站点数据失败:', error)
    stations.value = []
  } finally {
    loading.value = false
  }
}

// 初始化
onMounted(() => {
  fetchStations()
  
  // 点击外部关闭下拉菜单
  document.addEventListener('click', handleClickOutside)
})

// 清理事件监听器
onUnmounted(() => {
  document.removeEventListener('click', handleClickOutside)
})

// 点击外部关闭下拉菜单
const handleClickOutside = (event) => {
  // 如果点击的不是下拉菜单区域，则关闭所有下拉菜单
  if (!event.target.closest('.relative')) {
    showTypeDropdown.value = false
    showAccessDropdown.value = false
    showStatusDropdown.value = false
  }
}
</script>

<style scoped>
.animate-slide-up {
  animation: slideUp 0.2s ease-out;
}

@keyframes slideUp {
  from {
    opacity: 0;
    transform: translateY(-10px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

/* 确保下拉菜单层级最高，不被任何元素遮挡 */
.relative {
  position: relative;
  isolation: isolate;
}

.absolute {
  position: absolute;
}

/* 强制设置下拉菜单的 z-index，使用内联样式确保最高优先级 */
.z-\[100\] {
  z-index: 100 !important;
}

/* 为筛选区域创建新的层叠上下文 */
.grid > div {
  isolation: isolate;
}

/* 强制确保所有下拉菜单都在合适层级 */
[class*="showTypeDropdown"],
[class*="showAccessDropdown"], 
[class*="showStatusDropdown"] {
  z-index: 100 !important;
}

/* 使用通用选择器确保下拉菜单层级 */
.absolute[class*="dropdown"],
[class*="Dropdown"] {
  z-index: 100 !important;
}
</style>